package main

import (
	"bytes"
	"fmt"
	"io"
	"my-zinx/utils"
	"my-zinx/ziface"
	"my-zinx/znet"
	"net"
)

/** 自定义路由
不再局限于原HandleFunc的参数形式
*/

type VersionRouter struct {
	znet.BaseRouter
}

func (v *VersionRouter) Handle(r ziface.IRequest) {
	fmt.Printf("VersionRouter Goroutine Handle...\n")

	fmt.Printf("[Recv] MsgID:%d, Data:%s\n", r.GetMsgID(), r.GetData())

	data := bytes.NewBufferString(fmt.Sprintf("Hello Zinx, Version: %s\n", utils.Env.Version))

	if err := r.GetConnection().SendMsg(201, data.Bytes()); err != nil {
		fmt.Println("tcp connection write err: ", err)
	}
}

type HelloRouter struct {
	znet.BaseRouter
}

func (h *HelloRouter) Handle(r ziface.IRequest) {
	fmt.Printf("HelloRouter Goroutine Handle...\n")

	fmt.Printf("[Recv] MsgID:%d, Data:%s\n", r.GetMsgID(), r.GetData())

	data := bytes.NewBufferString(fmt.Sprintf("Hello Hello Hello...\n"))

	if err := r.GetConnection().SendMsg(301, data.Bytes()); err != nil {
		fmt.Println("tcp connection write err: ", err)
	}
}

func MainServer() {
	s := znet.NewServer()

	// 注册hook回调
	s.SetOnConnStart(func(conn ziface.IConnection) {
		fmt.Println("[Hook] OnConnectionStartFunc...")

		conn.SetProperty("A", "Snow")
		conn.SetProperty("B", "Flake")

		if err := conn.SendMsg(202, []byte("Begin...")); err != nil {
			return
		}
	})

	s.SetOnConnStop(func(conn ziface.IConnection) {
		fmt.Println("[Hook] OnConnectionStopFunc...")

		value, err := conn.GetProperty("A")
		if err != nil {
			return
		}
		fmt.Println("A: ", value)

		value, err = conn.GetProperty("B")
		if err != nil {
			return
		}
		fmt.Println("B: ", value)
	})

	s.AddRouter(200, &VersionRouter{})
	s.AddRouter(300, &HelloRouter{})

	s.Serve()
}

func main() {
	MainServer()
	//recvDataPack()
}

func recvDataPack() {
	listener, err := net.Listen("tcp", "127.0.0.1:7777")
	if err != nil {
		fmt.Println("listen err: ", err)
		return
	}

	fmt.Println("[Server] Start Zinx server success, now listening...")

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("accept err: ", err)
			return
		}

		go func(conn net.Conn) {
			dp := znet.NewDataPack()
			for {
				head := make([]byte, dp.GetHeadLen())
				_, err := io.ReadFull(conn, head)
				if err != nil {
					fmt.Println("read head err: ", err)
					break
				}

				msgHead, err := dp.Unpack(head)
				if err != nil {
					fmt.Println("data unpack err: ", err)
					return
				}

				if msgHead.GetDataLen() > 0 {
					msg := msgHead.(*znet.Message) // 类型断言
					msg.Data = make([]byte, msg.GetDataLen())

					_, err := io.ReadFull(conn, msg.Data)
					if err != nil {
						fmt.Println("read data err: ", err)
						return
					}

					fmt.Printf("==> [Recv] MsgID:%d, DataLen:%d, Data:%s\n", msg.ID, msg.DataLen, string(msg.Data))
				}
			}
		}(conn)
	}
}
